/*
 * @Author       : 魏威 <1209562577@qq.com>
 * @Date         : 2021-08-20 17:37 周5
 * @Description  : 工具方法
 */
import { useState, useEffect } from 'react';

export const isFalsy: (value: unknown) => boolean = (value) =>
  value === 0 ? false : !value;

/** 清理对象，删除没有的属性 */
export const cleanObject = (object: object) => {
  const result = { ...object };
  Object.keys(result).forEach((key) => {
    // @ts-ignore
    const value = result[key];
    if (isFalsy(value)) {
      // @ts-ignore
      delete result[key];
    }
  });
  return result;
};

export const useMount = (callback: () => void) => {
  useEffect(() => {
    callback();
  }, []);
};

export const useDebounced = <V>(value: V, delay?: number) => {
  const [debouncedValue, setDebouncedValue] = useState(value);
  useEffect(() => {
    const timeOut = setTimeout(() => setDebouncedValue(value), delay);
    return () => clearTimeout(timeOut);
  }, [value, delay]);
  return debouncedValue;
};
